package com.shiro_02.config;

import com.shiro_02.pojo.User;
import com.shiro_02.serivce.UserSerivce;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserSerivce userSerivce;
      //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
       // info.addStringPermission("user:add");
        Subject subject = SecurityUtils.getSubject();
        User principal = (User) subject.getPrincipal();
        //设置当前用户的权限
        info.addStringPermission(principal.getPerms());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行=》认证了");

        //获取用户 密码 数据中取
        UsernamePasswordToken usertoken =  (UsernamePasswordToken) token;
        User user = userSerivce.findUser(new User(usertoken.getUsername()));
        //获取当前的用户
        if (user==null) {
            return null;
        }

        //密码认证
        return  new SimpleAuthenticationInfo(user,user.getPassword(),"");

    }
}
